package com.cqut.forum.service.impl;

import java.io.File;

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import com.cqut.forum.dao.IPostDao;
import com.cqut.forum.entity.Post;
import com.cqut.forum.lucene.LuceneIndex;
import com.cqut.forum.service.ILuceneService;
import com.cqut.forum.service.IPostService;
import com.cqut.forum.util.ConfigProperties;



/**
* @ClassName: LuceneService
* @Description: TODO
* @author 刘强
* @date 2015-5-13 上午1:00:13
*/ 
@Service
public class LuceneService implements ILuceneService{
    private IPostDao postDao;
    private LuceneIndex luceneIndex;
 
    

	public IPostDao getPostDao() {
		return postDao;
	}

	public void setPostDao(IPostDao postDao) {
		this.postDao = postDao;
	}

	public LuceneIndex getLuceneIndex() {
		return luceneIndex;
	}

	public void setLuceneIndex(LuceneIndex luceneIndex) {
		this.luceneIndex = luceneIndex;
	}

	/* (non-Javadoc)
	 * @see com.cqut.forum.service.ILuceneService#luceneIndex()
	 * 读取XML文件，并将对应post对象添加到全文检索
	 */
	public void luceneIndex() {
		SAXReader reader = new SAXReader();
		String filePath = ConfigProperties.get("postidpath");
        File file = new File(filePath);
        Document document;
		try {
			if (file.exists()) {
			  document = reader.read(file);
			  Element root = document.getRootElement();// 得到根节点
			  Iterator iterator = root.elementIterator("id");
			  while(iterator.hasNext()){
				  Element id = (Element) iterator.next();
				  String postId=id.getText();
				  Post post=postDao.getPostById(Long.parseLong(postId));
				  if(null!=post){
					  luceneIndex.addIndex(post);
				  }
			  }
			  file.delete();
			  System.out.println("完成全文检索操作！");
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 读取XML文件
        
	}

	
}
